/*
 * License: Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 * Description: recv data impl
 * Date: 2019-12-02 15:37:46
 * LastEditTime : 2020-02-19 17:37:27
 */
#include <memory>
#include <numeric>
#include <sys/types.h>
#include <unistd.h>
#include "recv_data.h"
#include "trans_data.h"

using namespace std;
const int PRINT_INTERVAL = 500;
extern bool g_isFinished;
extern uint64_t g_channelNum;

uint64_t g_eosNum = 0;
const int MAX_STREAM = 512;
vector<uint32_t> g_streamFlag(MAX_STREAM, 0);

HIAI_StatusT UserDataRecvInterface::RecvData(const std::shared_ptr<void>& message)
{
    // if all channel are finished, set isFinished to true.
    std::shared_ptr<TransData> input = std::static_pointer_cast<TransData>(message);
    if (input == nullptr) {
        return HIAI_ERROR;
    }

    uint32_t index = input->channelId;
    if (index >= MAX_STREAM) {
        std::cout << "the channel index is invalid." << std::endl;
        return HIAI_ERROR;
    }
    g_streamFlag[index] = input->eos;

    int sum = accumulate(g_streamFlag.begin(), g_streamFlag.end(), 0);
    if (sum == g_channelNum) {
        g_isFinished = true;
    }

    if (input->frameId % PRINT_INTERVAL == 0) {
        string connectstr = input->isOutputConnected ? "Output connected" : "Output disconnected";
        pid_t pid = getpid();
        std::cout << "ProcessAliveStream:" << (g_channelNum - sum)
                  << " PID:" << pid
                  << " GraphID:" << input->graphId
                  << " DeviceID:" << input->deviceId
                  << " FrameID:" << input->frameId
                  << " TranscodeType:" << input->outputFormat
                  << " StreamPullFPS:" << input->streamPullFps
                  << " DecodeFPS:" << input->curDecodeFps
                  << " EncodeFPS:" << input->curEncodeFps
                  << " " << connectstr
                  << std::endl;
    }
    return HIAI_OK;
}
